<?php

namespace app\shop\model\goods;

use app\shop\library\ShopHelper;
use app\shop\model\BaseModel;
use app\shop\model\order\OrderEvaluateModel;
use think\model\concern\SoftDelete;
use think\model\relation\HasMany;

class GoodsModel extends BaseModel
{
    use SoftDelete;

    /**
     * @var string
     */
    protected $name = 'shop_goods';

    /**
     * @var string[]
     */
    protected $json = ['params'];

    /**
     * @var string[]
     */
    protected $append = [];

    /**
     * SKU关联
     * @return HasMany
     */
    public function sku(): HasMany
    {
        return $this->hasMany(GoodsSkuModel::class, 'goods_id', 'id');
    }

    /**
     * 评价关联
     * @return HasMany
     */
    public function evaluate(): HasMany
    {
        return $this->hasMany(OrderEvaluateModel::class, 'goods_id', 'id');
    }

    /**
     * 获取器：规格列表
     * @param $value
     * @return array|array[]
     * @noinspection PhpUnused
     */
    protected function getSpecListAttr($value): array
    {
        return array_map(function ($spec) {
            return [
                'name'  => $spec['name'],
                'value' => array_map(function ($value) {
                    return ['name' => $value];
                }, $spec['value'])
            ];
        }, ShopHelper::json_to_array($value));
    }

    /**
     * 获取器：SKU列表
     * @return mixed
     * @noinspection PhpMissingReturnTypeInspection
     */
    protected function getSkuListAttr()
    {
        foreach ($this->sku as &$sku) {
            $sku['spec']       = array_map(function ($item) {
                [$name, $value] = explode(':', $item);
                return [
                    'name'  => $name,
                    'value' => $value,
                ];
            }, array_filter(explode(';', $sku['spec'])));
            $sku['goods_name'] = $this->getData('name');
        }

        return $this->sku;
    }

    /**
     * 获取器：图片
     * @param $value
     * @return array|false|string[]
     * @noinspection PhpMissingReturnTypeInspection
     */
    public function getImagesAttr($value)
    {
        if (!$value) {
            return [];
        }

        return explode(',', $value);
    }

    /**
     * 获取器：图片详情
     * @param $value
     * @return array|false|string[]
     * @noinspection PhpUnused
     */
    public function getDetailImagesAttr($value): array|bool
    {
        if (!$value) {
            return [];
        }

        return explode(',', $value);
    }
}
